import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login, register, getUserInfo } from '@/api/user'
import { setToken, getToken, removeToken } from '@/utils/auth'

export const useUserStore = defineStore('user', () => {
  const token = ref(getToken())
  const userInfo = ref({})

  const loginAction = async (loginForm) => {
    try {
      const response = await login(loginForm)
      const { token: userToken, user } = response.data
      token.value = userToken
      userInfo.value = user
      setToken(userToken)
      return Promise.resolve()
    } catch (error) {
      return Promise.reject(error)
    }
  }

  const registerAction = async (registerForm) => {
    try {
      const response = await register(registerForm)
      const { token: userToken, user } = response.data
      token.value = userToken
      userInfo.value = user
      setToken(userToken)
      return Promise.resolve()
    } catch (error) {
      return Promise.reject(error)
    }
  }

  const logoutAction = () => {
    token.value = ''
    userInfo.value = {}
    removeToken()
  }

  const getUserInfoAction = async () => {
    try {
      const response = await getUserInfo()
      userInfo.value = response.data
      return Promise.resolve(response.data)
    } catch (error) {
      return Promise.reject(error)
    }
  }

  const checkLoginStatus = () => {
    if (token.value) {
      getUserInfoAction()
    }
  }

  return {
    token,
    userInfo,
    loginAction,
    registerAction,
    logoutAction,
    getUserInfoAction,
    checkLoginStatus
  }
})